<template><div><h2 id="认证" tabindex="-1"><a class="header-anchor" href="#认证"><span>认证</span></a></h2>
<p>Unlike Web applications, RESTful APIs are usually stateless, which means sessions or cookies should not be used. Therefore, each request should come with some sort of authentication credentials because the user authentication status may not be maintained by sessions or cookies. A common practice is to send a secret access token with each request to authenticate the user. Since an access token can be used to uniquely identify and authenticate a user, <strong>API requests should always be sent via HTTPS to prevent man-in-the-middle (MitM) attacks</strong>.</p>
<p>There are different ways to send an access token:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Basic_access_authentication" target="_blank" rel="noopener noreferrer">HTTP Basic Auth</a>: the access token is sent as the username. This should only be used when an access token can be safely stored on the API consumer side. For example, the API consumer is a program running on a server.</li>
<li>Query parameter: the access token is sent as a query parameter in the API URL, e.g., <code v-pre>https://example.com/users?access-token=xxxxxxxx</code>. Because most Web servers will keep query parameters in server logs, this approach should be mainly used to serve <code v-pre>JSONP</code> requests which cannot use HTTP headers to send access tokens.</li>
<li><a href="https://oauth.net/2/" target="_blank" rel="noopener noreferrer">OAuth 2</a>: the access token is obtained by the consumer from an authorization server and sent to the API server via <a href="https://datatracker.ietf.org/doc/html/rfc6750" target="_blank" rel="noopener noreferrer">HTTP Bearer Tokens</a>, according to the OAuth2 protocol.</li>
</ul>
<p>Yii supports all of the above authentication methods. You can also easily create new authentication methods.</p>
<p>To enable authentication for your APIs, do the following steps:</p>
<ol>
<li>Configure the <code v-pre>user</code> <a href="https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-application-components.md" target="_blank" rel="noopener noreferrer">application component</a>:
<ul>
<li>Set the [[yii\web\User::enableSession|enableSession]] property to be <code v-pre>false</code>.</li>
<li>Set the [[yii\web\User::loginUrl|loginUrl]] property to be <code v-pre>null</code> to show a HTTP 403 error instead of redirecting to the login page.</li>
</ul>
</li>
<li>Specify which authentication methods you plan to use by configuring the <code v-pre>authenticator</code> behavior in your REST controller classes.</li>
<li>Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]].</li>
</ol>
<p>Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]] is <code v-pre>false</code>, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication will be performed for every request, which is accomplished by Step 2 and 3.</p>
<blockquote>
<p>Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the <code v-pre>user</code> application component in application configurations if you are developing RESTful APIs in terms of an application. If you develop RESTful APIs as a module, you may put the following line in the module’s <code v-pre>init()</code> method, like the following:</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token keyword static-context">parent</span><span class="token operator">::</span><span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token class-name class-name-fully-qualified static-context"><span class="token punctuation">\</span>Yii</span><span class="token operator">::</span><span class="token variable">$app</span><span class="token operator">-></span><span class="token property">user</span><span class="token operator">-></span><span class="token property">enableSession</span> <span class="token operator">=</span> <span class="token constant boolean">false</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div></blockquote>
<p>For example, to use HTTP Basic Auth, you may configure the <code v-pre>authenticator</code> behavior as follows,</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>filters<span class="token punctuation">\</span>auth<span class="token punctuation">\</span>HttpBasicAuth</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">behaviors</span><span class="token punctuation">(</span><span class="token punctuation">)</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token variable">$behaviors</span> <span class="token operator">=</span> <span class="token keyword static-context">parent</span><span class="token operator">::</span><span class="token function">behaviors</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token variable">$behaviors</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'authenticator'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'class'</span> <span class="token operator">=></span> <span class="token class-name static-context">HttpBasicAuth</span><span class="token operator">::</span><span class="token keyword">class</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token keyword">return</span> <span class="token variable">$behaviors</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>If you want to support all three authentication methods explained above, you can use <code v-pre>CompositeAuth</code> like the following,</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>filters<span class="token punctuation">\</span>auth<span class="token punctuation">\</span>CompositeAuth</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>filters<span class="token punctuation">\</span>auth<span class="token punctuation">\</span>HttpBasicAuth</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>filters<span class="token punctuation">\</span>auth<span class="token punctuation">\</span>HttpBearerAuth</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>filters<span class="token punctuation">\</span>auth<span class="token punctuation">\</span>QueryParamAuth</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">behaviors</span><span class="token punctuation">(</span><span class="token punctuation">)</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token variable">$behaviors</span> <span class="token operator">=</span> <span class="token keyword static-context">parent</span><span class="token operator">::</span><span class="token function">behaviors</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token variable">$behaviors</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'authenticator'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span></span>
<span class="line">        <span class="token string single-quoted-string">'class'</span> <span class="token operator">=></span> <span class="token class-name static-context">CompositeAuth</span><span class="token operator">::</span><span class="token keyword">class</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token string single-quoted-string">'authMethods'</span> <span class="token operator">=></span> <span class="token punctuation">[</span></span>
<span class="line">            <span class="token class-name static-context">HttpBasicAuth</span><span class="token operator">::</span><span class="token keyword">class</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token class-name static-context">HttpBearerAuth</span><span class="token operator">::</span><span class="token keyword">class</span><span class="token punctuation">,</span></span>
<span class="line">            <span class="token class-name static-context">QueryParamAuth</span><span class="token operator">::</span><span class="token keyword">class</span><span class="token punctuation">,</span></span>
<span class="line">        <span class="token punctuation">]</span><span class="token punctuation">,</span></span>
<span class="line">    <span class="token punctuation">]</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token keyword">return</span> <span class="token variable">$behaviors</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>Each element in <code v-pre>authMethods</code> should be an auth method class name or a configuration array.</p>
<p>Implementation of <code v-pre>findIdentityByAccessToken()</code> is application specific. For example, in simple scenarios when each user can only have one access token, you may store the access token in an <code v-pre>access_token</code> column in the user table. The method can then be readily implemented in the <code v-pre>User</code> class as follows,</p>
<div class="language-php line-numbers-mode" data-highlighter="prismjs" data-ext="php" data-title="php"><pre v-pre class="language-php"><code><span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>db<span class="token punctuation">\</span>ActiveRecord</span><span class="token punctuation">;</span></span>
<span class="line"><span class="token keyword">use</span> <span class="token package">yii<span class="token punctuation">\</span>web<span class="token punctuation">\</span>IdentityInterface</span><span class="token punctuation">;</span></span>
<span class="line"></span>
<span class="line"><span class="token keyword">class</span> <span class="token class-name-definition class-name">User</span> <span class="token keyword">extends</span> <span class="token class-name">ActiveRecord</span> <span class="token keyword">implements</span> <span class="token class-name">IdentityInterface</span></span>
<span class="line"><span class="token punctuation">{</span></span>
<span class="line">    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">function</span> <span class="token function-definition function">findIdentityByAccessToken</span><span class="token punctuation">(</span><span class="token variable">$token</span><span class="token punctuation">,</span> <span class="token variable">$type</span> <span class="token operator">=</span> <span class="token constant">null</span><span class="token punctuation">)</span></span>
<span class="line">    <span class="token punctuation">{</span></span>
<span class="line">        <span class="token keyword">return</span> <span class="token keyword static-context">static</span><span class="token operator">::</span><span class="token function">findOne</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'access_token'</span> <span class="token operator">=></span> <span class="token variable">$token</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span></span>
<span class="line">    <span class="token punctuation">}</span></span>
<span class="line"><span class="token punctuation">}</span></span>
<span class="line"></span></code></pre>
<div class="line-numbers" aria-hidden="true" style="counter-reset:line-number 0"><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div><div class="line-number"></div></div></div><p>After authentication is enabled as described above, for every API request, the requested controller will try to authenticate the user in its <code v-pre>beforeAction()</code> step.</p>
<p>If authentication succeeds, the controller will perform other checks (such as rate limiting, authorization) and then run the action. The authenticated user identity information can be retrieved via <code v-pre>Yii::$app-&gt;user-&gt;identity</code>.</p>
<p>If authentication fails, a response with HTTP status 401 will be sent back together with other appropriate headers (such as a <code v-pre>WWW-Authenticate</code> header for HTTP Basic Auth).</p>
<h2 id="授权" tabindex="-1"><a class="header-anchor" href="#授权"><span>授权</span></a></h2>
<p>After a user is authenticated, you probably want to check if he or she has the permission to perform the requested action for the requested resource. This process is called <em>authorization</em> which is covered in detail in the <a href="https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md" target="_blank" rel="noopener noreferrer">Authorization section</a>.</p>
<p>If your controllers extend from [[yii\rest\ActiveController]], you may override the [[yii\rest\ActiveController::checkAccess()|checkAccess()]] method to perform authorization check. The method will be called by the built-in actions provided by [[yii\rest\ActiveController]].</p>
<blockquote>
<p>💖喜欢本文档的，欢迎点赞、收藏、留言或转发，谢谢支持！<br>
作者邮箱：zhuzixian520@126.com，github地址：<a href="https://github.com/zhuzixian520" target="_blank" rel="noopener noreferrer">github.com/zhuzixian520</a></p>
</blockquote>
</div></template>


